const express = require("express");

const app = express();

// const nw = (req, res, next) => {
//   console.log("调用了中间件");
//   next();
// };
// // 全局生效中间件
// app.use(nw);

app.use((req, res, next) => {
  console.log("全局中间件1的简化写法");
  // 获取请求到达服务器的时间
  const time = Date.now();
  // 为req对象，挂载自定义属性，把属性共享给后面所有路由（简化代码）
  req.startTime = time;
  next();
});
app.use((req, res, next) => {
  console.log("中间件2");
  next();
});

// 局部中间件
const nw1 = (req, res, next) => {
  console.log("调用了局部中间件1");
  next();
};
const nw2 = (req, res, next) => {
  console.log("调用了局部中间件2");
  next();
};

app.get("/user/age", (req, res) => {
  // 上面中间件共享的req对象属性，可以直接用
  res.send("This is age page,Method is get" + req.startTime);
});
app.post("/user/name", (req, res) => {
  res.send("This is name page,Method is post");
});
// 剧中中间件只在调用的路由中才有用
app.get("/next", [nw1, nw2], (req, res) => {
  res.send("This is Local Middleware");
});
app.listen(8080, () => {
  console.log("express server running at http://127.0.0.1:8080");
});
